package dongze.com.ckdj.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.bugly.beta.Beta;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import dongze.com.ckdj.BuildConfig;
import dongze.com.ckdj.CKDJApplication;
import dongze.com.ckdj.R;
import dongze.com.ckdj.dagger.DataStore;
import dongze.com.ckdj.dagger.component.DaggerSectionComponent;
import dongze.com.ckdj.dagger.component.DaggerUserComponent;
import dongze.com.ckdj.dagger.component.SectionComponent;
import dongze.com.ckdj.dagger.component.UserComponent;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.dagger.module.SectionModule;
import dongze.com.ckdj.dagger.module.UserModule;
import dongze.com.ckdj.data.entity.response.BrandResponse;
import dongze.com.ckdj.data.entity.response.InspectionSectionResponse;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.databinding.ActivitySignInBinding;
import dongze.com.ckdj.databinding.model.ProcessingModel;
import dongze.com.ckdj.databinding.model.SignInModel;
import dongze.com.ckdj.map.MapUtil;
import io.reactivex.observers.DisposableObserver;

import static android.view.KeyEvent.KEYCODE_ENTER;

/**
 * Created by Administrator on 2017/7/18.
 */
public class SignInActivity extends BaseActivity {
    private final int QR_REQUEST = 1024;
    @BindView(R.id.password_edittext)
    EditText mPasswordEdit;
    @BindView(R.id.user_name_edittext)
    EditText mUserNamePasswordEdit;
    View mPasswordParent;
    ProcessingModel processingModel = new ProcessingModel();
    SignInModel signInModel = new SignInModel();
    MapUtil mapUtil;
    boolean isDoingSignIn = false;

    @Inject
    DataStore dataStore;
    @Inject
    CKDJApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getAppCompenent().inject(this);
        app.finishAllActtivity();
        addComponent(UserComponent.class, null);
        addComponent(VehicleComponent.class, null);
        dataStore.clear();
        super.onCreate(savedInstanceState);

        if (!BuildConfig.DEBUG)
            Beta.checkUpgrade(true, false);

        mapUtil = new MapUtil(getAppCompenent());

//        if (getSupportActionBar() != null) {
//            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
//            getSupportActionBar().setDisplayShowHomeEnabled(false);
//        }

        ActivitySignInBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_sign_in, null, false);
        binding.setProgress(processingModel);
        binding.setSignIn(signInModel);
        setContentView(binding.getRoot());
        ButterKnife.bind(this);
        mUserNamePasswordEdit.setOnEditorActionListener(mOnEditorActionListener);
        mPasswordEdit.setOnEditorActionListener(mOnEditorActionListener);
        mPasswordEdit.setOnFocusChangeListener(mOnPasswordFocusChangedListener);
        mPasswordParent = (View) mPasswordEdit.getParent();

    }

    @Override
    protected void setActionBarButton() {
        mLeft.setVisibility(View.INVISIBLE);
        mRight.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onDestroy() {
        addComponent(UserComponent.class, null);
        dataStore.set(User.class, null);
        mapUtil.dispose();
        super.onDestroy();
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.password_forgot:
                Intent intent = new Intent();
                intent.setClass(this, PasswordForgotActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;

            case R.id.sign_in_btn:
                doSignIn();
                break;

            case R.id.sign_up_btn:
                intent = new Intent();
                intent.setClass(this, SignUpActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;

            case R.id.scanner:
                doQRSignIn();
                break;
        }
    }

    private void doSignIn() {
        if (isDoingSignIn)
            return;

        if (signInModel.name.get() == null || signInModel.name.get().length() == 0) {
            Toast.makeText(this, "user name nust not be empty", Toast.LENGTH_SHORT).show();
            return;
        }

//        if (mPasswordEdit.getText() == null || mPasswordEdit.getText().length() == 0) {
//            Toast.makeText(this, "password nust not be empty", Toast.LENGTH_SHORT).show();
//            return;
//        }

        isDoingSignIn = true;
        processingModel.visible.set(true);
        mapUtil.login(signInModel.name.get(), mPasswordEdit.getText().toString(), new DisposableObserver<User>() {
            @Override
            public void onNext(User value) {
                processingModel.visible.set(false);
                onLogInSuccess(value);
            }

            @Override
            public void onError(Throwable e) {
                isDoingSignIn = false;
                processingModel.visible.set(false);
                new AlertDialog.Builder(SignInActivity.this)
                        .setTitle("登陆失败")
                        .setMessage(e.getMessage())
                        .create()
                        .show();
            }

            @Override
            public void onComplete() {
                isDoingSignIn = false;
            }
        });
    }

    private void doQRSignIn() {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(this, QRScannerActivity.class));

        // testcode
//        intent.putExtra("format", BarcodeFormat.CODE_39.name());
//        intent.putExtra("regular", "^[0-9]*-[0-9]*$");

        startActivityForResult(intent, QR_REQUEST);
    }

    private void onQRRecgnized(String code) {
        mUserNamePasswordEdit.setText(code);
        doSignIn();
    }

    private void onLogInSuccess(User user) {
        Toast.makeText(SignInActivity.this, "login success,user:" + user.getUser_name(), Toast.LENGTH_SHORT).show();
        dataStore.set(User.class, user);
        addComponent(UserComponent.class,
                DaggerUserComponent.builder()
                        .appComponent(getAppCompenent())
                        .userModule(new UserModule(user))
                        .build());
        /**
         * 数据写死 宝马 港建
         */
        String brand_str = "{\"brand_code\":\"11\",\"brand_name\":\"宝马\",\"is_check\":\"1.0\",\"sort\":\"2.0\"}";
        BrandResponse brand = new Gson().fromJson(brand_str, BrandResponse.class);
        String ins_str = "{\"brand_code\":\"11\",\"brand_name\":\"宝马\",\"create_time\":\"Aug 4, 2017 11:37:22 AM\",\"max_times\":1,\"node_code\":\"103\",\"node_name\":\"港检\",\"state\":1,\"top_node\":\"\"}\n";
        InspectionSectionResponse inspectionSection = new Gson().fromJson(ins_str, InspectionSectionResponse.class);
        CKDJApplication application = (CKDJApplication)getApplicationContext();
        if (brand != null && inspectionSection != null && application.getComponent(UserComponent.class) != null) {
            dataStore.set(BrandResponse.class, brand);
            dataStore.set(InspectionSectionResponse.class, inspectionSection);
            SectionComponent sectionComponent = DaggerSectionComponent.builder()
                    .sectionModule(new SectionModule(brand, inspectionSection))
                    .userComponent(application.getComponent(UserComponent.class))
                    .build();
            application.addComponent(SectionComponent.class, sectionComponent);
            startActivity(new Intent(this, CheckInActivity.class));
        }
//        Intent intent = new Intent();
//        intent.setComponent(new ComponentName(getApplicationContext(), UserPreferenceActivity.class));
//        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == QR_REQUEST) {
            if (resultCode == RESULT_OK) {
                final String code = data.getStringExtra("code");
                Toast.makeText(this, "QRcode = " + code, Toast.LENGTH_SHORT).show();
                new Handler(getMainLooper())
                        .post(new Runnable() {
                            @Override
                            public void run() {
                                onQRRecgnized(code);
                            }
                        });
                return;
            } else {
                Toast.makeText(this, "qr scan failed", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private View.OnFocusChangeListener mOnPasswordFocusChangedListener = new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                mPasswordParent.getBackground().setState(new int[]{android.R.attr.state_focused, android.R.attr.state_enabled});
            } else {
                mPasswordParent.getBackground().setState(new int[]{android.R.attr.state_enabled});
            }
        }
    };

    private TextView.OnEditorActionListener mOnEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (EditorInfo.IME_ACTION_DONE == actionId || (event != null && event.getKeyCode() == KEYCODE_ENTER)) {
                doSignIn();
                return true;
            }
            return false;
        }
    };
}
